//
//  TJUserDataListViewModel.swift
//  WeiBo
//
//  Created by TanJian on 15/12/9.
//  Copyright © 2015年 Joshpell. All rights reserved.
//

import UIKit

class TJUserDataListViewModel: NSObject {

    //装每条微博模型的数组
    var userInfoList:[TJUserDataViewModel]?
    
    //加载微博数据，并告诉外界请求成功与否
    func loadData(isPull:Bool,complete:(isSuccess:Bool,count:Int)->()){
        
        //如果是上拉状态，则需要刷新，取到最后一条微博的id
        var maxID = isPull == true ? (userInfoList?.last?.status?.id ?? 0):0
        //如果是上啦刷新，取到第一条微博的id
        let minID = isPull == true ? 0:(userInfoList?.first?.status?.id ?? 0)
        if maxID > 0{
            maxID -= 1
        }
        TJHttpTool.shareTool.loadStatus(TJUserAcountViewModel.shareViewModel.accessToken!, minID: minID, maxID: maxID) { (response, error) -> () in
            if error != nil{
                complete(isSuccess: false,count: 0)

                return
            }
            
            //数据请求成功
            guard let result = response as? [String:AnyObject] else{
                print("返回数据不是一个字典")
                return
            }
            
            guard let statusDict = result["statuses"] as? [[String:AnyObject]] else{
                print("没有statuses")
                return
            }
            var tempArray = [TJUserDataViewModel]()
            
            //遍历，转换成模型
            
            for value in statusDict{
                

                let status = TJUserData(dict: value)
                tempArray.append(TJUserDataViewModel(userData: status))
                
            }
            
            if self.userInfoList == nil{
                self.userInfoList = [TJUserDataViewModel]()
            }
            
            if isPull{
                //拼接到后面
                self.userInfoList = self.userInfoList! + tempArray
            }else{
                self.userInfoList = tempArray + self.userInfoList!
            }
            

            complete(isSuccess: true,count: tempArray.count)
            
        }
        
        
    }
    
}
